$(document).ready(function () {
    $('#ConfirmRuleDialogModal').modal({
        backdrop: 'static', 
        keyboard: false
    })
    $("#login-btn").on("click", function() {
        if (loginValidate()) {
            var data = { phoneNumber: $("#phoneNumber").val(), inputPassword: $("#inputPassword").val() };
            var url = "../Handle/LogHandlerService.ashx?method=Verification_User_Log";
            $.ajax({
                type: "POST",
                data: data,
                url: url,
                dataType: "json",
                success: function (data) {
                    // console.info(data);
                    if (10 == data.MessageType) {
                        $("#dialog-modal-label").text("该用户被限制登录，请联系单位管理员！");
                        $("#DialogModal").modal("show");
                    } else if (1 == data.MessageType) {
                        if($("#remember-me").is(':checked')) {
                            Cookies.set('gxskIdentify', $("#phoneNumber").val(), { expires: 7, path: '' });
                            Cookies.set('gxskKey', $("#inputPassword").val(), { expires: 7, path: '' });
                        } else {
                            Cookies.remove('gxskIdentify', { path: '' });
                            Cookies.remove('gxskKey', { path: '' });
                        }
                        // top.location="../Family/Main.aspx";
                        top.location="../Family/MyBooks.aspx";
                    } else {
                        // alert("登录信息错误，请重新登录！");
                        $("#dialog-modal-label").text("登录信息错误，请重新登录！");
                        $("#DialogModal").modal("show");
                    }
                    //console.log(data);
                }
            });
        }
    });

    $("#confirm-rule").on("click", function(){
        $("#confirm-rule").removeAttr("checked");
        $("#ConfirmRuleDialogModal").modal("show");
    });

    $("#confirm-rule-btn").on("click", function(){
        $("#confirm-rule").prop("checked","checked");
        $("#ConfirmRuleDialogModal").modal("hide");
    })
    
    fillFormByCookies();

    $(document)
        .on('click', '.list-group-item', function() {
            window.open("TBook.aspx?BID="+$(this).attr("value"), "_self");
        })

    fetchBorrowedCountResult();
    fetchStarCountResult();
    fetchCommentsCountResult();
    fetchNewestBooksResult();

    $("#ConfirmRuleDialogModal").modal("show");

});

function fillFormByCookies() {
    if (Cookies.get("gxskIdentify") && Cookies.get("gxskKey")) {
        $("#phoneNumber").val(Cookies.get("gxskIdentify"));
        $("#inputPassword").val(Cookies.get("gxskKey"));
        $("#remember-me").attr("checked","true");
    }
}

function loginValidate() {
    return $("#login-form").validate({
        errorClass: "warning",
        rules: {
            phoneNumber: {
                required: true,
                digits:true,
                minlength: 11,
                maxlength: 11,
            },
            inputPassword: {
                required: true,
                minlength: 5
            },
            confirmRule: {
                required: true,
            },
        },
        messages: {
            phoneNumber: {
                required: "请输入电话号码",
                digits: "电话号码是数字",
                minlength: "电话号码有11位数字",
                maxlength: "电话号码有11位数字"
            },
            inputPassword: {
                required: "请输入密码",
                minlength: "密码长度不能小于 5 个字母"
            },
            confirmRule: {
                required: "请先同意书吧规则",
            },
        }
    }).form();
}

function buildListHtml(items, dimension, styleClass) {
    if (!items) {
        return;
    }
    if (0 == items.length) {
        return "<li class='list-group-item list-group-item-"+styleClass+"'>暂无记录</li>"
    }
    var outputHtml = "";
    var listNum = items.length>3?3:items.length;
    for (var k = 0; k < listNum; k++) {
        var dateStr = ""+items[k][dimension];
        //dateStr = dateStr.substring(2,dateStr.length); 
        outputHtml += "<li style='cursor:pointer' class='list-group-item list-group-item-"+styleClass+"' value='" + items[k]["图书编号"] + 
        "'>《" + subStrToLimitLength(items[k]["图书名称"], 5) + "》<span class='badge'>" + dateStr + "</span></li>";
    }
    return outputHtml;
}

function fetchBorrowedCountResult() {
    $.ajax({
        type: "POST",
        data: { ProcedureID: 1},
        url: "../Handle/OtherHandlerService.ashx?method=Ad_Report_Get_Summary_List",
        dataType: "json",
        success: function (data) {
            $("#borrowed-count-list").html(buildListHtml(data.rows, "借阅数量", "success"));
        }
    });
}

function fetchStarCountResult() {
    $.ajax({
        type: "POST",
        data: { ProcedureID: 4},
        url: "../Handle/OtherHandlerService.ashx?method=Ad_Report_Get_Summary_List",
        dataType: "json",
        success: function (data) {
            // console.log(data);
            $("#star-count-list").html(buildListHtml(data.rows, "星级数量", "info"));
        }
    });
}

function fetchCommentsCountResult() {
    $.ajax({
        type: "POST",
        data: { ProcedureID: 3},
        url: "../Handle/OtherHandlerService.ashx?method=Ad_Report_Get_Summary_List",
        dataType: "json",
        success: function (data) {
            //console.log(data);
            $("#comments-count-list").html(buildListHtml(data.rows, "书评数量", "warning"));
        }
    });
}

function fetchNewestBooksResult() {
    $.ajax({
        type: "POST",
        data: { ProcedureID: 12},
        url: "../Handle/OtherHandlerService.ashx?method=Ad_Report_Get_Summary_List",
        dataType: "json",
        success: function (data) {
            //console.log(data);
            $("#newest-books-list").html(buildListHtml(data.rows, "入库日期", "danger"));
        }
    });
}

function subStrToLimitLength(str, length) {
    if (!str) { return "";}
    return (str.length <= length) ? str : (str.substr(0, [(length - 1)]) + "...");
}
